package com.jds.test.proto;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Created by sunyuming on 18/8/1.
 */
class ServerHandler4V2 extends SimpleChannelInboundHandler<MyBaseProtoV2.BaseProto> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MyBaseProtoV2.BaseProto msg) throws Exception {
        System.out.println("RESPONSE--------"+msg.toString());

        MyBaseProtoV2.BaseProto.Builder builder = MyBaseProtoV2.BaseProto.newBuilder();
        builder.setCode(msg.getCode() + 200);
        builder.setMsg("server" + msg.getCode());
        MyBaseProtoV2.Body.Builder bodyBuilder = MyBaseProtoV2.Body.newBuilder();
        bodyBuilder.setNewField(String.valueOf(msg.getCode() + "new msg for client"));
        builder.setResult(bodyBuilder.build());

        ctx.writeAndFlush(builder.build()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if(!channelFuture.isSuccess()) {
                    channelFuture.cause().printStackTrace();
                    channelFuture.channel().close();
                }
            }
        });

    }

    //新客户端接入
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive");
    }

    //客户端断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelInactive");
    }

    //异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.channel().close();
        //打印异常
        cause.printStackTrace();
    }
}